package com.hecj.common.lib.util;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Encoder;

/**
 * Created by ZHANYIFEI611 on 2016-08-23.
 */
public class HttpUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    public final static String FAILURE_MESSAGE = "failure_message";

    /**
     * post 方法
     *
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, List<NameValuePair> params) {
        HttpClient hc = null;
        HttpPost httppost = null;
        if (url.toLowerCase().startsWith("https")) {
            hc = wrapClient(new DefaultHttpClient());
        } else {
            hc = new DefaultHttpClient();
        }
        String body = null;
        try {
            httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httppost.setHeader("Accept", "application/json;charset=utf-8");
            //设置关闭
            httppost.setHeader("Connection", "close");
            HttpResponse httpresponse = hc.execute(httppost);
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            //释放资源
            EntityUtils.consume(entity);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }
    public static String   get(String url) {
        HttpClient hc = null;
        HttpGet httpGet = null;
        if (url.toLowerCase().startsWith("https")) {
            hc = wrapClient(new DefaultHttpClient());
        } else {
            hc = new DefaultHttpClient();
        }
        String body = null;
        try {
            httpGet = new HttpGet(new URI(url));
            httpGet.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpGet.setHeader("Accept", "application/json;charset=utf-8");
            //设置关闭
            httpGet.setHeader("Connection", "close");
            HttpResponse httpresponse = hc.execute(httpGet);
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            
            //释放资源
            EntityUtils.consume(entity);
        } catch (Exception e) {
        	e.printStackTrace();
            return FAILURE_MESSAGE;
        }
        return body;
    }

    public static DefaultHttpClient wrapClient(
            HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] arg0,
                                               String arg1) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] arg0,
                                               String arg1) throws CertificateException {
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx,
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("https", 8443, ssf));
            ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(
                    registry);
            return new DefaultHttpClient(mgr, base.getParams());
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    public static String base64Encode(String param, String code) {
        byte[] bytes = null;
        try {
            bytes = param.getBytes(code);
        } catch (UnsupportedEncodingException e) {
            logger.error("base64Encode Exception", e);
        }

        String base64 = new BASE64Encoder().encode(bytes);
        return base64;
    }
    
    public static String getOneHost(String urlStr){
    	java.net.URL url;
		try {
			url = new java.net.URL(urlStr);
			String host = url.getHost();// 获取主机名
			return host;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return "";
    }
    
}
